// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <melon/ip_address.h>

#include <pollux/type/simple_function_api.h>
#include <pollux/type/type.h>

namespace kumo::pollux {
    namespace ipaddress {
        constexpr int kIPV4AddressBytes = 4;
        constexpr int kIPV4ToV6FFIndex = 10;
        constexpr int kIPV4ToV6Index = 12;
        constexpr int kIPAddressBytes = 16;

        inline melon::ByteArray16 toIPv6ByteArray(const int128_t &ipAddr) {
            melon::ByteArray16 bytes{{0}};
            memcpy(bytes.data(), &ipAddr, sizeof(ipAddr));
            // Reverse because the pollux is always on little endian system
            // and the byte array needs to be big endian (network byte order)
            std::reverse(bytes.begin(), bytes.end());
            return bytes;
        }

        inline melon::Expected<int128_t, melon::IPAddressFormatError>
        tryGetIPv6asInt128FromString(const std::string &ipAddressStr) {
            auto maybeIp = melon::IPAddress::tryFromString(ipAddressStr);
            if (maybeIp.hasError()) {
                return melon::makeUnexpected(maybeIp.error());
            }

            int128_t intAddr;
            melon::IPAddress addr = maybeIp.value();
            auto addrBytes = melon::IPAddress::createIPv6(addr).toByteArray();
            std::reverse(addrBytes.begin(), addrBytes.end());
            memcpy(&intAddr, &addrBytes, kIPAddressBytes);
            return intAddr;
        }
    } // namespace ipaddress

    class IPAddressType : public HugeintType {
        IPAddressType() : HugeintType(/*providesCustomComparison*/ true) {
        }

    public:
        static const std::shared_ptr<const IPAddressType> &get() {
            static const std::shared_ptr<const IPAddressType> instance{
                new IPAddressType()
            };

            return instance;
        }

        int32_t compare(const int128_t &left, const int128_t &right) const override {
            const auto leftAddrBytes = ipaddress::toIPv6ByteArray(left);
            const auto rightAddrBytes = ipaddress::toIPv6ByteArray(right);
            return memcmp(
                leftAddrBytes.begin(),
                rightAddrBytes.begin(),
                ipaddress::kIPAddressBytes);
        }

        uint64_t hash(const int128_t &value) const override {
            return melon::hasher<int128_t>()(value);
        }

        bool equivalent(const Type &other) const override {
            // Pointer comparison works since this type is a singleton.
            return this == &other;
        }

        const char *name() const override {
            return "IPADDRESS";
        }

        std::string toString() const override {
            return name();
        }

        melon::Dynamic serialize() const override {
            melon::Dynamic obj = melon::Dynamic::object;
            obj["name"] = "Type";
            obj["type"] = name();
            return obj;
        }
    };

    MELON_ALWAYS_INLINE bool isIPAddressType(const TypePtr &type) {
        // Pointer comparison works since this type is a singleton.
        return IPAddressType::get() == type;
    }

    MELON_ALWAYS_INLINE std::shared_ptr<const IPAddressType> IPADDRESS() {
        return IPAddressType::get();
    }

    // Type used for function registration.
    struct IPAddressT {
        using type = int128_t;
        static constexpr const char *typeName = "ipaddress";
    };

    using IPAddress = CustomType<IPAddressT, /*providesCustomComparison*/ true>;
} // namespace kumo::pollux
